<template>
  <div class="chat-list">
    <div class="chat-header">
      <h2>私聊消息</h2>
      <div class="header-actions">
        <el-button type="primary" @click="handleNewChat" size="small">
          <el-icon><Plus /></el-icon>
          新聊天
        </el-button>
        <el-button 
          size="small" 
          type="danger" 
          plain
          @click="handleReport"
          class="report-button"
        >
          <el-icon><Warning /></el-icon>
          举报
        </el-button>
      </div>
    </div>

    <div class="search-box">
      <el-input
        v-model="searchKeyword"
        placeholder="搜索用户UID或用户名..."
        prefix-icon="Search"
        clearable
        @keyup.enter="searchUserByUid"
      />
      <el-button 
        type="primary" 
        @click="searchUserByUid"
        :loading="searching"
        class="search-btn"
      >
        搜索
      </el-button>
    </div>

    <!-- 搜索结果 -->
    <div v-if="searchResult" class="search-result">
      <div class="search-result-item">
        <el-avatar :size="40" :src="searchResult.avatar" />
        <div class="user-info">
          <span class="user-name">{{ searchResult.name }}</span>
          <span class="user-uid">UID: {{ searchResult.id }}</span>
        </div>
        <el-button type="primary" size="small" @click="startChatWithUser(searchResult)">
          发起聊天
        </el-button>
      </div>
    </div>

    <div class="chat-items">
      <div
        v-for="chat in filteredChats"
        :key="chat.id"
        class="chat-item"
        :class="{ active: selectedChat?.id === chat.id }"
        @click="selectChat(chat)"
      >
        <div class="chat-avatar">
          <el-avatar :size="48" :src="getChatAvatar(chat)" />
          <div v-if="chat.unreadCount > 0" class="unread-badge">
            {{ chat.unreadCount > 99 ? '99+' : chat.unreadCount }}
          </div>
        </div>
        
        <div class="chat-info">
          <div class="chat-header-info">
            <span class="chat-name">{{ getChatName(chat) }}</span>
            <span class="chat-time">{{ formatTime(chat.lastMessageTime) }}</span>
          </div>
          <div class="chat-preview">
            <p class="last-message">{{ getLastMessagePreview(chat.lastMessage) }}</p>
          </div>
          <div class="chat-uid">
            UID: {{ getChatUid(chat) }}
          </div>
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <div v-if="filteredChats.length === 0 && !searchKeyword" class="empty-chats">
      <el-empty description="暂无聊天记录" />
      <el-button type="primary" @click="handleNewChat">
        发起新聊天
      </el-button>
    </div>

    <!-- 搜索空状态 -->
    <div v-if="filteredChats.length === 0 && searchKeyword && !searchResult" class="empty-search">
      <el-empty description="未找到相关聊天记录" />
    </div>
  </div>

  <!-- 举报对话框 -->
  <el-dialog
    v-model="showReportDialog"
    title="举报用户"
    width="500px"
    align-center
  >
    <el-form
      ref="reportFormRef"
      :model="reportForm"
      :rules="reportRules"
      label-width="80px"
    >
      <el-form-item label="用户UID" prop="targetUid">
        <el-input 
          v-model="reportForm.targetUid" 
          placeholder="请输入要举报的用户UID"
        />
      </el-form-item>
      
      <el-form-item label="举报内容" prop="content">
        <el-input
          v-model="reportForm.content"
          type="textarea"
          :rows="4"
          placeholder="请详细描述举报原因..."
          maxlength="500"
          show-word-limit
        />
      </el-form-item>
      
      <el-form-item label="举报图片">
        <el-upload
          action="#"
          list-type="picture-card"
          :file-list="reportForm.images"
          :on-change="handleImageChange"
          :on-remove="handleImageRemove"
          :auto-upload="false"
          :limit="3"
          accept="image/*"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>
        <div class="upload-tip">最多上传3张图片，每张不超过2MB</div>
      </el-form-item>
    </el-form>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="showReportDialog = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="submitReport"
          :loading="submittingReport"
        >
          提交举报
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus, Warning } from '@element-plus/icons-vue'

const props = defineProps({
  chats: {
    type: Array,
    default: () => []
  },
  currentUser: {
    type: Object,
    required: true
  }
})

const emit = defineEmits(['select-chat', 'new-chat', 'search-user'])

const searchKeyword = ref('')
const selectedChat = ref(null)
const searching = ref(false)
const searchResult = ref(null)

// 举报相关状态
const showReportDialog = ref(false)
const submittingReport = ref(false)
const reportFormRef = ref()

// 举报表单数据
const reportForm = reactive({
  targetUid: '',
  content: '',
  images: []
})

// 表单验证规则
const reportRules = {
  targetUid: [
    { required: true, message: '请输入用户UID', trigger: 'blur' },
    { pattern: /^\d+$/, message: 'UID必须为数字', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入举报内容', trigger: 'blur' },
    { min: 10, message: '举报内容至少10个字符', trigger: 'blur' }
  ]
}

// 举报处理
const handleReport = () => {
  // 初始化表单数据
  reportForm.targetUid = ''
  reportForm.content = ''
  reportForm.images = []
  
  showReportDialog.value = true
}

// 图片上传处理
const handleImageChange = (file) => {
  // 检查文件大小
  if (file.size > 2 * 1024 * 1024) {
    ElMessage.error('图片大小不能超过2MB')
    return false
  }
  
  // 检查文件类型
  if (!file.raw.type.startsWith('image/')) {
    ElMessage.error('只能上传图片文件')
    return false
  }
  
  // 添加到图片列表
  reportForm.images.push({
    name: file.name,
    url: URL.createObjectURL(file.raw),
    raw: file.raw
  })
}

// 图片移除处理
const handleImageRemove = (file) => {
  const index = reportForm.images.findIndex(item => item.uid === file.uid)
  if (index !== -1) {
    reportForm.images.splice(index, 1)
  }
}

// 提交举报
const submitReport = async () => {
  if (!reportFormRef.value) return
  
  try {
    // 验证表单
    await reportFormRef.value.validate()
    
    submittingReport.value = true
    
    // 构建表单数据
    const formData = new FormData()
    formData.append('targetUid', reportForm.targetUid)
    formData.append('content', reportForm.content)
    formData.append('reporterUid', props.currentUser.id)
    formData.append('reporterName', props.currentUser.name)
    
    // 添加图片文件
    reportForm.images.forEach((image, index) => {
      formData.append(`images`, image.raw)
    })
    
    // 模拟提交到后端API
    console.log('提交举报数据:', {
      targetUid: reportForm.targetUid,
      content: reportForm.content,
      images: reportForm.images.length,
      reporterUid: props.currentUser.id
    })
    
    // 模拟API请求
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success('举报提交成功，管理员将在24小时内处理')
    showReportDialog.value = false
    
    // 重置表单
    reportFormRef.value.resetFields()
    reportForm.images = []
    
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    submittingReport.value = false
  }
}

// 过滤聊天列表
const filteredChats = computed(() => {
  if (!searchKeyword.value) {
    searchResult.value = null
    return props.chats
  }
  
  const keyword = searchKeyword.value.toLowerCase()
  const filtered = props.chats.filter(chat => {
    const chatName = getChatName(chat).toLowerCase()
    const chatUid = getChatUid(chat).toString()
    const lastMessage = chat.lastMessage?.content?.toLowerCase() || ''
    
    return chatName.includes(keyword) || 
           lastMessage.includes(keyword) ||
           chatUid.includes(keyword)
  })
  
  // 如果没有找到聊天记录，清空搜索结果
  if (filtered.length === 0) {
    searchResult.value = null
  }
  
  return filtered
})

// 通过UID搜索用户
const searchUserByUid = async () => {
  if (!searchKeyword.value.trim()) {
    ElMessage.warning('请输入用户UID或用户名')
    return
  }

  searching.value = true
  try {
    // 触发父组件搜索用户
    emit('search-user', searchKeyword.value.trim())
  } catch (error) {
    console.error('搜索用户失败:', error)
    ElMessage.error('搜索用户失败')
  } finally {
    searching.value = false
  }
}

// 设置搜索结果
const setSearchResult = (user) => {
  searchResult.value = user
}

// 获取聊天UID
const getChatUid = (chat) => {
  if (chat.type === 'private') {
    return chat.participant.id
  }
  return chat.groupId || ''
}

// 获取聊天头像
const getChatAvatar = (chat) => {
  if (chat.type === 'private') {
    return chat.participant.avatar
  }
  return chat.groupAvatar || ''
}

// 获取聊天名称
const getChatName = (chat) => {
  if (chat.type === 'private') {
    return chat.participant.name
  }
  return chat.groupName || '群聊'
}

// 获取最后消息预览
const getLastMessagePreview = (lastMessage) => {
  if (!lastMessage) return '暂无消息'
  
  let content = lastMessage.content
  if (lastMessage.type === 'image') {
    content = '[图片]'
  } else if (lastMessage.type === 'file') {
    content = '[文件]'
  } else if (lastMessage.type === 'system') {
    content = '[系统消息]'
  }
  
  // 截断长文本
  return content.length > 20 ? content.substring(0, 20) + '...' : content
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  
  const now = new Date()
  const targetTime = new Date(time)
  const diff = now - targetTime
  
  if (diff < 60000) {
    return '刚刚'
  } else if (diff < 3600000) {
    return `${Math.floor(diff / 60000)}分钟前`
  } else if (diff < 86400000) {
    return `${Math.floor(diff / 3600000)}小时前`
  } else if (diff < 604800000) {
    return `${Math.floor(diff / 86400000)}天前`
  } else {
    return targetTime.toLocaleDateString('zh-CN', {
      month: 'short',
      day: 'numeric'
    })
  }
}

// 选择聊天
const selectChat = (chat) => {
  selectedChat.value = chat
  emit('select-chat', chat)
}

// 发起新聊天
const handleNewChat = () => {
  searchKeyword.value = ''
  searchResult.value = null
  emit('new-chat')
}

// 与用户开始聊天
const startChatWithUser = (user) => {
  searchKeyword.value = ''
  searchResult.value = null
  emit('new-chat', user)
}

// 暴露方法给父组件
defineExpose({
  setSearchResult
})
</script>

<style scoped>
.chat-list {
  width: 350px;
  height: 100%;
  background: white;
  border-right: 1px solid #e5e7eb;
  display: flex;
  flex-direction: column;
}

.chat-header {
  padding: 16px;
  border-bottom: 1px solid #e5e7eb;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chat-header h2 {
  margin: 0;
  font-size: 1.25rem;
  color: #1f2937;
}

.header-actions {
  display: flex;
  gap: 8px;
  align-items: center;
}

.search-box {
  padding: 12px 16px;
  border-bottom: 1px solid #e5e7eb;
  display: flex;
  gap: 8px;
}

.search-btn {
  flex-shrink: 0;
}

.search-result {
  padding: 12px 16px;
  border-bottom: 1px solid #e5e7eb;
  background: #f8fafc;
}

.search-result-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  background: white;
  border-radius: 8px;
  border: 1px solid #e5e7eb;
}

.user-info {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.user-name {
  font-weight: 600;
  color: #1f2937;
  font-size: 0.875rem;
}

.user-uid {
  font-size: 0.75rem;
  color: #6b7280;
}

.chat-items {
  flex: 1;
  overflow-y: auto;
}

.chat-item {
  display: flex;
  padding: 12px 16px;
  cursor: pointer;
  border-bottom: 1px solid #f3f4f6;
  transition: background-color 0.2s;
}

.chat-item:hover {
  background-color: #f9fafb;
}

.chat-item.active {
  background-color: #e8f5e8;
  border-right: 3px solid #4caf50;
}

.chat-avatar {
  position: relative;
  margin-right: 12px;
}

.unread-badge {
  position: absolute;
  top: -4px;
  right: -4px;
  background: #ff4757;
  color: white;
  border-radius: 10px;
  padding: 2px 6px;
  font-size: 0.75rem;
  min-width: 18px;
  text-align: center;
  line-height: 1;
}

.chat-info {
  flex: 1;
  min-width: 0;
}

.chat-header-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 4px;
}

.chat-name {
  font-weight: 600;
  color: #1f2937;
  font-size: 0.875rem;
}

.chat-time {
  font-size: 0.75rem;
  color: #9ca3af;
}

.chat-preview {
  margin-bottom: 4px;
}

.last-message {
  margin: 0;
  font-size: 0.875rem;
  color: #6b7280;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.chat-uid {
  font-size: 0.75rem;
  color: #9ca3af;
}

.empty-chats {
  padding: 40px 20px;
  text-align: center;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.empty-search {
  padding: 40px 20px;
  text-align: center;
}

/* 举报相关样式 */
.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 举报按钮样式 */
.report-button {
  margin-left: 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .chat-header {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }
  
  .header-actions {
    justify-content: space-between;
  }
  
  .search-box {
    flex-direction: column;
  }
  
  .search-btn {
    width: 100%;
    margin-top: 8px;
  }
}
</style>